import 'dart:async';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

class MainPlayerState with ChangeNotifier {
  // 音频播放器实例对象
  AudioPlayer audioPlayer = AudioPlayer();

  // 音频当前时间
  Duration position;

  // 音频是否正在播放
  bool complete = false;

  double timing = 30;
  int audioIndex = 0;

  var timer;
  var playing;

  setPlaying(item, index) {
    playing = item;
    audioIndex = index;
    reload();
  }

  setSliderValue(v) {
    timing = v;
    notifyListeners();
  }

  setTimer() {
    if (timer == null) {
      timer = Timer.periodic(Duration(seconds: 60), (t) {
        timing = timing >= 1 ? timing - 1 : 0;
        notifyListeners();
        if (timing <= 1) {
          pause();
          timer?.cancel();
          timer = null;
          notifyListeners();
        }
      });
    } else {
      timer?.cancel();
      timer = null;
    }
    notifyListeners();
  }

  reload() {
    position = Duration(milliseconds: 0);
    play();
    notifyListeners();
  }

  void init() async {
    audioPlayer.onPlayerStateChanged.listen((state) {
      // 播放完毕 重置时长及播放状态
      if (state == AudioPlayerState.COMPLETED) reload();
    });

    // 播放进度监听
    audioPlayer.onAudioPositionChanged.listen((Duration p) {
      position = p;
      notifyListeners();
    });
  }

  // 开始播放
  play() async {
    final result = await audioPlayer.play(playing['audio'], position: position);
    audioPlayer.setPlaybackRate(playbackRate: 1.0);
    if (result == 1) {
      complete = true;
      notifyListeners();
    }
  }

  // 暂停播放
  void pause() async {
    final result = await audioPlayer.pause();
    if (result == 1) {
      complete = false;
      notifyListeners();
    }
  }

  //停止播放
  void stop() {
    audioPlayer.stop();
  }

  void setSeek(seek) {
    audioPlayer.seek(seek);
  }
}
